package timer;

import java.util.concurrent.BlockingQueue;
import java.util.concurrent.PriorityBlockingQueue;

//任务
class MyTask implements Comparable<MyTask> {
    //准备执行的任务
    private Runnable runnable;
    //何时执行
    private long time;

    public MyTask(Runnable runnable, long delay) {
        this.runnable = runnable;
        this.time = delay + System.currentTimeMillis();
    }
    public Runnable getRunnable() {
        return runnable;
    }
    public long getTime() {
        return time;
    }
    public int compareTo(MyTask o) {//这里时间是long类型，需要强制类型转换，单位是毫秒
        return (int)(this.time - o.time);
    }
}
//定时器
class MyTimer {
    //用使用优先级阻塞队列
    private BlockingQueue<MyTask> queue = new PriorityBlockingQueue<>();
    public Object locker = new Object();
    public MyTimer() {
        //这是一个扫描线程
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                //一直扫描要执行的任务
                while (true) {
                    try {
                        //加锁保证原子性,
                        synchronized(locker) {
                            //取出队首元素
                            MyTask task = queue.take();
                            long curTime = System.currentTimeMillis();
                            //到点了该执行任务
                            if (curTime >= task.getTime()) {
                                task.getRunnable().run();
                            } else {//否则就阻塞等待
                                //还没到点就放回去
                                queue.put(task);
                                //没到点就等待
                                locker.wait(task.getTime() - curTime);
                            }
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();
    }

    public void schedule(Runnable runnable, long after) throws InterruptedException {
        MyTask task = new MyTask(runnable, after);
        queue.put(task);
        synchronized(locker){
            locker.notify();
        }
    }
}

public class Test {
    public static void main(String[] args) throws InterruptedException {
        MyTimer timer = new MyTimer();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("时间到1");
            }
        }, 3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("时间到2");
            }
        }, 4000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("时间到3");
            }
        }, 5000);
        System.out.println("开始计时");
    }
}
